const express=require('express');
const router=express.Router();
const query = require('../mysql')
const jwt = require('../utils/jwt')

//获取角色
router.get('/getRole',function(req,res){
    const page = (req.query.pageNum-1)*req.query.pageSize
    var  sql = `SELECT * FROM my_role`;
    query(sql,function (err,result,) {
        console.log(result)
        if(err){ //sql 语句报错
            res.send({code:202,data:err,msg:"错误"})
            return;
        }else{
            res.send({code:200,data:result,msg:"ok"})
        }
    })
});

// 新增角色
router.post('/addRole',function (req,res){
    let sql=''
    if(req.body.id){
        sql = `update my_role set name= '${req.body.name}' where id = ${req.body.id}`;
    }else{
        sql = `INSERT INTO my_role (name) VALUES ('${req.body.name}')`;
    }
    query(sql,function (err,result,) {
        if(err){ //sql 语句报错
            res.send({code:202,data:err,msg:"错误"})
            return;
        }else{
            res.send({code:200,data:true,msg:"ok"})
        }
    })
})

//删除角色
router.post('/delRole',function(req,res){
    const sql = `DELETE FROM my_role WHERE id = '${req.body.id}'`;
    query(sql,function (err,result,) {
        if(err){ //sql 语句报错
            res.send({code:202,data:err,msg:"错误"})
            return;
        }else{
            res.send({code:200,data:true,msg:"ok"})
        }
    })
});

//
router.get('/getUsersByRole',function(req,res){
    const sql = `SELECT mu.* FROM my_user mu 
    JOIN user_role ur ON mu.id = ur.user_id
    JOIN my_role mr ON ur.role_id = mr.id
    WHERE mr.id = ${req.query.id}`;
    query(sql,function (err,result,) {
        if(err){ //sql 语句报错
            res.send({code:202,data:err,msg:"错误"})
            return;
        }else{
            res.send({code:200,data:result,msg:"ok"})
        }
    })
})

router.post('/addUserByRole',function(req,res){
    const roleId  = req.body.roleId
    const userId =  req.body.userId
    const str = userId.map(item=>`('${roleId}','${item}')`).join(',')
    const sqlDel =   `DELETE FROM user_role WHERE role_id = '${roleId}'`
    var  sql = `insert into user_role (role_id,user_id) values ${str}`;
    console.log(sql)
    query(sqlDel,function(err,result){
        if(err){ //sql 语句报错
            res.send({code:202,data:err,msg:"错误"})
            return;
        }else{
            query(sql,function (err,result,) {
                if(err){ //sql 语句报错
                    res.send({code:202,data:err,msg:"错误"})
                    return;
                }else{
                    res.send({code:200,data:true,msg:"ok"})
                }
            })
        }
    })
    // query(sql,function (err,result,) {
    //     if(err){ //sql 语句报错
    //         res.send({code:202,data:err,msg:"错误"})
    //         return;
    //     }else{
    //         res.send({code:200,data:true,msg:"ok"})
    //     }
    // })
})

module.exports = router
